<?php
/**
 * 创建条形码
 * User: lxl
 * Date: 2020/09/05
 */
namespace App\Library\Service;

use App\Traits\SingleInstanceTrait;
use Picqer\Barcode\BarcodeGeneratorHTML;
use Picqer\Barcode\BarcodeGeneratorJPG;
use Picqer\Barcode\BarcodeGeneratorPNG;
use Picqer\Barcode\BarcodeGeneratorSVG;

class BarcodeService
{
    use SingleInstanceTrait;

    /**
     * PNG条码图
     * @param $barcode
     * @param $dst_dir
     * @param string $type
     * @param int $widthFactor
     * @param int $height
     * @param $foregroundColor
     * @param string $format
     * @return array
     */
    public function generatorBarcode($barcode, $dst_dir, $type = BarcodeGeneratorPNG::TYPE_CODE_128, int $widthFactor = 2, int $height = 30, $foregroundColor = [0, 0, 0], $format = 'png')
    {
        $barcode = trim($barcode);
        if (empty($barcode)) {
            return alert_info(1, '条形码不能为空');
        }
        if (empty($type)) {
            $type = BarcodeGeneratorPNG::TYPE_CODE_128;
        }
        $args = func_get_args();
        $md5 = md5(serialize($args));
        $dst_dir = $dst_dir . DIRECTORY_SEPARATOR . substr($md5, 0, 2) . DIRECTORY_SEPARATOR;
        if (!is_dir($dst_dir)) {
            easy_mk_dir(easy_attached_path($dst_dir));
        }
        $file = $dst_dir . $md5 . '.' . $format;
        $url = easy_attached($file);
        $file_path = easy_attached_path($file);
        if (file_exists($file_path)) {
            return alert_info(0, 'ok', $url);
        }
        switch ($format) {
            case 'svg':
                $generator = new BarcodeGeneratorSVG();
                $foregroundColor = '';
                break;
            case 'png':
                $generator = new BarcodeGeneratorPNG();
                break;
            case 'jpg':
                $generator = new BarcodeGeneratorJPG();
                $foregroundColor = '';
                break;
            case 'html':
                $generator = new BarcodeGeneratorHTML();
                $foregroundColor = '';
                break;
            default:
                return alert_info(1, '不支持的类型格式');
        }
        $res = $generator->getBarcode($barcode, $type, $widthFactor, $height, $foregroundColor);
        file_put_contents($file_path, $res);
        if (file_exists($file_path) === false) {
            return alert_info(1, '生成条形码失败');
        }
        return alert_info(0, 'ok', easy_attached($file));
    }
}
